import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'sputil.dart';

class TokenModel {
  final String username;
  final String name;
  final String role;
  final String token;
  bool authed;

  TokenModel(
      {required this.username,
      required this.name,
      required this.role,
      required this.token,
      this.authed = false});

  factory TokenModel.fromJson(Map<String, dynamic> json) {
    return TokenModel(
        username: json["username"],
        name: json["name"],
        role: json["role"],
        token: json["token"],
        authed: true);
  }
  factory TokenModel.empty() {
    return TokenModel(username: '', name: '', role: '', token: '');
  }
}

Future<TokenModel> api_login(context, String username, String password) async {
  TokenModel result = TokenModel.empty();
  try {
    final response = await http.post(
      Uri.parse('https://rtc.jxt.elef.top:8086/user/token'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(
          <String, String>{'username': username, 'password': password}),
    );

    print(response.statusCode);

    if (response.statusCode == 200) {
      //print(response.body);

      final item = json.decode(new Utf8Decoder().convert(response.bodyBytes));
      result = TokenModel.fromJson(item);

      var spu = SpUtil();
      spu.setString("token", result.token);

      print(spu.get<String>("token"));
    } else {}
  } catch (e) {
    print(e);
  }
  return result;
}

class UserProvider with ChangeNotifier {
  TokenModel user = TokenModel.empty();
  bool loading = false;

  Login(context, String username, String password) async {
    loading = true;
    user = await api_login(context, username, password);
    loading = false;

    notifyListeners();
  }
}
